"use client";

import React, { createContext, useState, useEffect, ReactNode, useLayoutEffect } from "react";

const defaultState = {
    routes: [],
    customerId: "",
    ZhiJis: [] as Record<string, string | number>[],
    userName: "",
    superAdmin: false,
    loading: true,
};

export const GlobalStateContext = createContext<{
    state: typeof defaultState;
    setState?: React.Dispatch<React.SetStateAction<typeof defaultState>>;
    setUserInfo?: (user: { userName: string }) => void;
    fetchUserInfo?: () => Record<string, any>;
}>({ state: defaultState });

export const GlobalStateProvider = ({ children }: { children: ReactNode }) => {
    const [state, setState] = useState({ ...defaultState });

    useEffect(() => {
        if (state.userName == "admin") {
        }
    }, [state.userName]);

    const fetchUserInfo = () => {
        const userInfo = localStorage.getItem("userInfo");

        const parseInfo = JSON.parse(userInfo || "{}") as Record<string, any>;

        setState(p => ({
            ...p,
            userName: parseInfo.userName,
        }));

        return parseInfo;
    };

    const setUserInfo = (user: { userName: string }) => {
        setState(p => ({
            ...p,
            userName: user.userName,
        }));
        localStorage.setItem("userInfo", JSON.stringify({ userName: user.userName }));
    };

    // useEffect(() => {
    useLayoutEffect(() => {
        fetchUserInfo();

        // console.log("parseInfo:", parseInfo);

        // console.log(parseInfo.userName);
        // console.log(parseInfo.loginDate);

        // fetch("/api/route")
        //     .then<RouteResponse>(r => r.json())
        //     .then(res => {
        //         setState(p => ({
        //             ...p,
        //             routes: res.list,
        //         }));

        //         if (parseInfo.userName && parseInfo.loginDate) {
        //             if (new Date().getTime() - new Date(parseInfo.loginDate).getTime() > 604800000) {
        //                 console.log("登陆超过7天 重新登陆");
        //             } else {
        //                 setState(p => ({
        //                     ...p,
        //                     userName: parseInfo.userName,
        //                     superAdmin: parseInfo.superAdmin,
        //                 }));
        //                 // setState(p => ({
        //                 //     ...p,
        //                 //     routes:
        //                 //         parseInfo.userName == "admin"
        //                 //             ? [...res.list, { title: "数据库维护", link: "/db" }]
        //                 //             : res.list,
        //                 //     userName: parseInfo.userName,
        //                 // }));
        //             }
        //         }
        //     })
        //     .catch(err => {
        //         console.log("路由获取失败☹️", err);
        //     }).finally(() => {
        //         setState(p => ({
        //             ...p,
        //             loading: false,
        //         }));
        //     });

        // fetch("/api/customer")
        //     .then<RouteResponse>(r => r.json())
        //     .then(res => {
        //         console.log("customer:", res);
        //     })
        //     .catch(err => {
        //         console.log("客户信息获取失败☹️", err);
        //     });

        // fetch("/api/cacheZhiJis")
        //     .then<{ list: Array<Record<string, string>> }>(r => r.json())
        //     .then(res => {
        //         console.log("cacheZhiJis:", res.list);
        //         setState(state => ({
        //             ...state,
        //             ZhiJis: res.list,
        //         }));
        //     })
        //     .catch(err => {
        //         console.log("缓存实时监控获取失败☹️", err);
        //     });
        console.log("CONTEXT");
        setState(p => ({
            ...p,
            loading: false,
        }));
    }, []);

    return (
        <GlobalStateContext.Provider value={{ state, setState, setUserInfo, fetchUserInfo }}>
            {children}
        </GlobalStateContext.Provider>
    );
};
